<template>
  <div class="app-container home">
    <a-card v-if="router_list.length == 0">
      <a-statistic title="系统提示" :value="'欢迎使用工泰运营商平台！'" class="demo-class" :value-style="{ color: '#3f8600' }">
      </a-statistic>
    </a-card>
    <div v-if="router_list.length > 0">
      <a-card title="数据总览" class="mt10" v-if="checkPermi(['statistics:home'])">
        <a-row>
          <a-col class="col_5 main_group">
            <a-row>
              <a-col :lg="4">
                <div class="main_img operator"></div>
              </a-col>
              <a-col :lg="20">
                <div class="main_title">子运营商数量</div>
                <div class="main_value">{{ info.subOperator || 0 }}</div>
              </a-col>
            </a-row>
          </a-col>
          <a-col class="col_5 main_group">
            <a-row>
              <a-col :lg="4">
                <div class="main_img station"></div>
              </a-col>
              <a-col :lg="20">
                <div class="main_title">电站数量</div>
                <div class="main_value">{{ info.stationCount || 0 }}</div>
              </a-col>
            </a-row>
          </a-col>
          <a-col class="col_5 main_group">
            <a-row>
              <a-col :lg="4">
                <div class="main_img dev"></div>
              </a-col>
              <a-col :lg="20">
                <div class="main_title">设备数量</div>
                <div class="main_value">{{ info.devCount || 0 }}</div>
              </a-col>
            </a-row>
          </a-col>
          <a-col class="col_5 main_group">
            <a-row>
              <a-col :lg="4">
                <div class="main_img"></div>
              </a-col>
              <a-col :lg="20">
                <div class="main_title"></div>
                <div class="main_value"></div>
              </a-col>
            </a-row>
          </a-col>
          <a-col class="col_5 main_group">
            <a-row>
              <a-col :lg="4">
                <div class="main_img"></div>
              </a-col>
              <a-col :lg="20">
                <div class="main_title"></div>
                <div class="main_value"></div>
              </a-col>
            </a-row>
          </a-col>
        </a-row>
      </a-card>
      <a-card title="设备统计" class="mt10" v-if="checkPermi(['statistics:home'])">
        <a-row :gutter="20">
          <a-col :lg="8" class="dev_group">
            <a-card>
              <div class="dev_state on">在线</div>
              <div class="dev_value">{{ info.devOnlineCount || 0 }}</div>
            </a-card>
          </a-col>
          <a-col :lg="8" class="dev_group">
            <a-card>
              <div class="dev_state off">离线</div>
              <div class="dev_value">{{ info.devOfflineCount || 0 }}</div>
            </a-card>
          </a-col>
          <a-col :lg="8" class="dev_group">
            <a-card>
              <div class="dev_state error">故障</div>
              <div class="dev_value">{{ info.devErrorCount || 0 }}</div>
            </a-card>
          </a-col>
        </a-row>
      </a-card>
      <el-row :gutter="20" class="mt10"
        v-if="checkPermi(['statistics:home', 'statistics:order:count', 'statistics:rank:station'])">
        <el-col :lg="16">
          <a-card title="日营收统计" v-if="checkPermi(['statistics:home'])">
            <a-row>
              <el-col :lg="12">
                <div class="today_group">
                  <div class="today_title">流水总金额（元）</div>
                  <div class="today_value all_value">
                    <span class="today_unit">￥</span>
                    {{ info.todayIncome ? (info.todayIncome / 100).toFixed(2) : 0 }}
                  </div>
                </div>
                <div class="today_group">
                  <div class="today_title">微信流水（元）</div>
                  <div class="today_value">
                    <span class="today_unit">￥</span>
                    {{ info.todayWxIncome ? (info.todayWxIncome / 100).toFixed(2) : 0 }}
                  </div>
                </div>
                <div class="today_group">
                  <div class="today_title">支付宝流水（元）</div>
                  <div class="today_value">
                    <span class="today_unit">￥</span>
                    {{ info.todayAliIncome ? (info.todayAliIncome / 100).toFixed(2) : 0 }}
                  </div>
                </div>
                <div class="today_group">
                  <div class="today_title">余额流水（元）</div>
                  <div class="today_value">
                    <span class="today_unit">￥</span>
                    {{ info.todayBalIncome ? (info.todayBalIncome / 100).toFixed(2) : 0 }}
                  </div>
                </div>
              </el-col>
              <el-col :lg="12">
                <div id="chartPie"></div>
              </el-col>
            </a-row>
          </a-card>
          <a-card title="总充电订单数" v-if="checkPermi(['statistics:order:count'])">
            <template #extra>
              <div class="line_group">
                <div class="left">
                  <a-radio-group v-model:value="queryOrder.group" @change="changeStatistics">
                    <a-radio-button :value="1">日</a-radio-button>
                    <a-radio-button :value="2">周</a-radio-button>
                    <a-radio-button :value="3">月</a-radio-button>
                    <a-radio-button :value="4">年</a-radio-button>
                  </a-radio-group>
                </div>
                <div class="right">
                  <a-radio-group v-model:value="line_type" @change="changeType" button-style="solid">
                    <a-radio-button value="charge">充电订单</a-radio-button>
                    <a-radio-button value="elec">耗电量</a-radio-button>
                    <a-radio-button value="user">活跃用户</a-radio-button>
                  </a-radio-group>
                </div>
              </div>
            </template>
            <div class="orderSts" ref="orderSts"></div>
          </a-card>
        </el-col>
        <el-col :lg="8" class="rank_group" v-if="checkPermi(['statistics:rank:station'])">
          <a-card :title="rankStr + '电站收入排行榜'">
            <template #extra>
              <a-radio-group v-model:value="queryOrder.group" @change="changeStatistics">
                <a-radio-button :value="1">日</a-radio-button>
                <a-radio-button :value="2">周</a-radio-button>
                <a-radio-button :value="3">月</a-radio-button>
                <a-radio-button :value="4">年</a-radio-button>
              </a-radio-group>
            </template>
            <el-table :data="rank">
              <el-table-column label="排序" align="left" width="55">
                <template #default="scope">
                  <span :class="'rank_value rank_value_' + scope.row.rankValue">{{ scope.row.rankValue }}</span>
                </template>
              </el-table-column>
              <el-table-column label="电站名称" align="left" prop="stationName" />
              <el-table-column label="电量" align="center" prop="electricity">
                <template #default="scope">
                  <span>{{ (scope.row.electricity / 3600000).toFixed(2) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="收入" align="right" prop="income">
                <template #default="scope">
                  <span>{{ scope.row.income / 100 }}</span>
                </template>
              </el-table-column>
            </el-table>
          </a-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup name="Index">
import { rankStation, orderCount, statistics } from "@/api/trade/statistics";
import { checkPermi } from "@/utils/permission";
import * as echarts from 'echarts';

const version = ref('3.8.5')

const rank = ref([])
const count = ref({})
const info = ref({})
const line_type = ref("charge")
const orderStr = ref("日")
const rankStr = ref("今日")
const router_list = ref([])
const orderSts = ref(null);

const data = reactive({
  queryOrder: {
    group: 1
  },
  querySts: {
    beginTime: undefined,
    endTime: undefined,
  },
});

const { queryOrder, querySts } = toRefs(data);
function refresh() {
  let now_time = new Date();
  const year = now_time.getFullYear();
  const month = now_time.getMonth();
  const day = now_time.getDate();
  const week = now_time.getDay();
  switch (queryOrder.value.group) {
    case 1:
      orderStr.value = "日"
      rankStr.value = "今日"
      let start_day = formatDate(now_time);
      let end_day = formatDate(new Date(now_time.getTime() + 24 * 60 * 60 * 1000));
      querySts.value.beginTime = start_day + " 00:00:00"
      querySts.value.endTime = end_day + " 00:00:00"
      break;
    case 2:
      orderStr.value = "周"
      rankStr.value = "本周"
      let start_week = formatDate(new Date(year, month, day - week + 1));
      let end_week = formatDate(new Date(year, month, day - week + 7));
      console.log(start_week, end_week)
      querySts.value.beginTime = start_week + " 00:00:00"
      querySts.value.endTime = end_week + " 00:00:00"
      break;
    case 3:
      orderStr.value = "月"
      rankStr.value = "本月"
      let start_month = formatDateMonth(new Date(now_time.getTime()));
      let end_month = formatDate(new Date(now_time.getTime() + 24 * 60 * 60 * 1000));
      querySts.value.beginTime = start_month + "-01 00:00:00"
      querySts.value.endTime = end_month + " 00:00:00"
      break;
    case 4:
      orderStr.value = "年"
      rankStr.value = "今年"
      let start_year = formatDateYear(new Date(now_time.getTime()));
      let end_year = formatDate(new Date(now_time.getTime() + 24 * 60 * 60 * 1000));
      querySts.value.beginTime = start_year + "-01-01 00:00:00"
      querySts.value.endTime = end_year + " 00:00:00"
      break;
  }
  getRankStation()
  getOrderCount()
  getStatistics()
}

function getRankStation() {
  rankStation(querySts.value).then((response) => {
    rank.value = response.data
    for (let i = 0; i < rank.value.length; i++) {
      rank.value[i].rankValue = i + 1
    }
  })
}
function getOrderCount() {
  orderCount(queryOrder.value).then((response) => {
    count.value = response.data
    createLine()
  })
}
function getStatistics() {
  statistics().then((response) => {
    info.value = response.data
  })
}

function changeStatistics(e) {
  queryOrder.value.group = e.target.value
  let now_time = new Date();
  const year = now_time.getFullYear();
  const month = now_time.getMonth();
  const day = now_time.getDate();
  const week = now_time.getDay();
  switch (queryOrder.value.group) {
    case 1:
      orderStr.value = "日"
      rankStr.value = "今日"
      let start_day = formatDate(now_time);
      let end_day = formatDate(new Date(now_time.getTime() + 24 * 60 * 60 * 1000));
      querySts.value.beginTime = start_day + " 00:00:00"
      querySts.value.endTime = end_day + " 00:00:00"
      break;
    case 2:
      orderStr.value = "周"
      rankStr.value = "本周"
      let start_week = formatDate(new Date(year, month, day - week + 1));
      let end_week = formatDate(new Date(year, month, day - week + 7));
      console.log(start_week, end_week)
      querySts.value.beginTime = start_week + " 00:00:00"
      querySts.value.endTime = end_week + " 00:00:00"
      break;
    case 3:
      orderStr.value = "月"
      rankStr.value = "本月"
      let start_month = formatDateMonth(new Date(now_time.getTime()));
      let end_month = formatDate(new Date(now_time.getTime() + 24 * 60 * 60 * 1000));
      querySts.value.beginTime = start_month + "-01 00:00:00"
      querySts.value.endTime = end_month + " 00:00:00"
      break;
    case 4:
      orderStr.value = "年"
      rankStr.value = "今年"
      let start_year = formatDateYear(new Date(now_time.getTime()));
      let end_year = formatDate(new Date(now_time.getTime() + 24 * 60 * 60 * 1000));
      querySts.value.beginTime = start_year + "-01-01 00:00:00"
      querySts.value.endTime = end_year + " 00:00:00"
      break;
  }
  getRankStation()
  getOrderCount()
}

function changeType(e) {
  line_type.value = e.target.value
}

function createLine() {
  let date = []
  let aliOrderCount = []
  let balOrderCount = []
  let totalCount = []
  let wxOrderCount = []
  let now_time = new Date();
  const year = now_time.getFullYear();
  const month = now_time.getMonth();
  for (let i = 0; i < count.value.length; i++) {
    switch (queryOrder.value.group) {
      case 1:
        date.push(count.value[i].date + ":00")
        break;
      case 4:
        date.push(count.value[i].date + "月")
        break;
      default:
        date.push((month + 1) + "月" + count.value[i].date + "日")
        break;
    }
    balOrderCount.push(count.value[i].balOrderCount)
    aliOrderCount.push(count.value[i].aliOrderCount)
    totalCount.push(count.value[i].totalCount)
    wxOrderCount.push(count.value[i].wxOrderCount)
  }
  const orderStsIntance = echarts.init(orderSts.value, "orderStsLine");
  orderStsIntance.setOption({
    tooltip: { trigger: "axis" },
    xAxis: { type: "category", data: date, },
    yAxis: { type: "value" },
    series: [
      {
        data: totalCount,
        name: "订单总数",
        type: "line",
        label: {
          show: true,
          position: "outside",
        },
      },
      {
        data: wxOrderCount,
        name: "微信订单数",
        type: "line",
        label: {
          show: true,
          position: "outside",
        },
      },
      {
        data: aliOrderCount,
        type: "line",
        name: "支付宝订单数",
        label: {
          show: true,
          position: "outside",
        },
      },
      {
        data: balOrderCount,
        type: "line",
        name: "余额订单数",
        label: {
          show: true,
          position: "outside",
        },
      },
    ],
  });
}


function goTarget(url) {
  window.open(url, '__blank')
}

// 格式化时间（HH:mm:ss）
function formatTime(date) {
  let hour = date.getHours(); // 时
  hour = hour < 10 ? "0" + hour : hour; // 如果只有一位，则前面补零
  let minute = date.getMinutes(); // 分
  minute = minute < 10 ? "0" + minute : minute; // 如果只有一位，则前面补零
  let second = date.getSeconds(); // 秒
  second = second < 10 ? "0" + second : second; // 如果只有一位，则前面补零
  let nowDate = `${hour}:${minute}:${second}`;
  return nowDate;
}

// 格式化时间（yy-MM-dd）
function formatDate(date) {
  let year = date.getFullYear(); // 年
  let month = date.getMonth() + 1; // 月
  month = month < 10 ? "0" + month : month; // 如果只有一位，则前面补零
  let day = date.getDate(); // 日
  day = day < 10 ? "0" + day : day; // 如果只有一位，则前面补零
  let nowDate = `${year}-${month}-${day}`;
  return nowDate;
}
// 格式化时间（uu-MM）
function formatDateMonth(date) {
  let year = date.getFullYear(); // 年
  let month = date.getMonth() + 1; // 月
  month = month < 10 ? "0" + month : month; // 如果只有一位，则前面补零
  // let day = date.getDate(); // 日
  // day = day < 10 ? "0" + day : day; // 如果只有一位，则前面补零
  let nowDate = `${year}-${month}`;
  return nowDate;
}
// 格式化时间（uu-MM）
function formatDateYear(date) {
  let year = date.getFullYear(); // 年
  let nowDate = `${year}`;
  return nowDate;
}
router_list.value = JSON.parse(window.localStorage.getItem("router"))
refresh();
</script>

<style scoped lang="scss">
.home {
  min-height: calc(100vh - 84px);
  background: #f3f4fd;

  blockquote {
    padding: 10px 20px;
    margin: 0 0 20px;
    font-size: 17.5px;
    border-left: 5px solid #eee;
  }

  hr {
    margin-top: 20px;
    margin-bottom: 20px;
    border: 0;
    border-top: 1px solid #eee;
  }

  .col-item {
    margin-bottom: 20px;
  }

  ul {
    padding: 0;
    margin: 0;
  }

  font-family: "open sans",
  "Helvetica Neue",
  Helvetica,
  Arial,
  sans-serif;
  font-size: 13px;
  color: #676a6c;
  overflow-x: hidden;

  ul {
    list-style-type: none;
  }

  h4 {
    margin-top: 0px;
  }

  h2 {
    margin-top: 10px;
    font-size: 26px;
    font-weight: 100;
  }

  p {
    margin-top: 10px;

    b {
      font-weight: 700;
    }
  }

  .update-log {
    ol {
      display: block;
      list-style-type: decimal;
      margin-block-start: 1em;
      margin-block-end: 1em;
      margin-inline-start: 0;
      margin-inline-end: 0;
      padding-inline-start: 40px;
    }
  }
}

.col_5 {
  width: 20%;
}

.main_group {
  .main_value {
    margin: 5px 0;
    font-size: 20px;
    font-weight: bold;
  }

  .main_img {
    width: 50px;
    height: 50px;
    margin-top: 5px;

    &.operator {
      background-image: url("../assets/images/operator.png");
      background-size: cover;
    }

    &.station {
      background-image: url("../assets/images/station.png");
      background-size: cover;
    }

    &.dev {
      background-image: url("../assets/images/dev.png");
      background-size: cover;
    }
  }
}

.dev_group {

  .ant-card:deep() {
    background: #efefef85;
  }

  .dev_value {
    margin: 5px 0;
    font-size: 20px;
    font-weight: bold;
  }

  .dev_state {
    position: relative;
    margin-left: 10px;

    &::before {
      content: " ";
      display: block;
      position: absolute;
      left: -15px;
      top: 6px;
      width: 10px;
      height: 10px;
      background: #333333;
      border-radius: 50%;
    }

    &.on::before {
      background: #00ff00;
    }

    &.error::before {
      background: #ff0000;
    }
  }
}

.today_group {

  .today_title {
    color: #666666;
  }

  .today_value {
    margin: 5px 0;
    font-weight: bold;

    &.all_value {
      font-size: 20px;
    }

    .today_unit {
      font-size: 14px;
      font-weight: bold;
    }
  }
}

.line_group {
  .left {
    float: left;
    margin-right: 10px;
  }

  .right {
    float: right;
  }
}

.rank_group {
  .rank_title {
    margin-right: 5px;
  }

  .use_percentage {
    font-size: 24px;
    font-weight: bold;
  }

  .rank_value {
    display: block;
    width: 28px;
    height: 28px;
    line-height: 28px;
    font-size: 14px;
    background: #666666;
    color: #efefef;
    border-radius: 50%;
    text-align: center;

    &.rank_value_1 {
      background: #ff0000;
    }

    &.rank_value_2 {
      background: #ff9900;
    }

    &.rank_value_3 {
      background: #ffee00;
    }
  }
}

.orderSts {
  width: 100%;
  height: 300px;
}
</style>

